import Promise from 'promise';
import validator from 'validator';
import * as ResultMsg from '../constrants/ResultMsg';
import { errorJson, successJson } from '../common/response';
import { checkId, checkDoc, checkDocs } from '../common/check';
import { ProfileProxy } from '../proxy';

export {
  data,
  update,
  create,
};

async function data(req, res, next) {
  const appId = res.locals.appId || '';

  try {
    const doc = await ProfileProxy.findOne(appId);
    successJson(req, res, { data: doc });
  } catch (err) {
    next(err);
  }
}

async function update(req, res, next) {
  const appId = res.locals.appId || '';
  const id = validator.trim(req.body.id || '');
  const guide = validator.trim(req.body.guide || '');
  const isHtml = req.body.isHtml || false;

  const data = {
    guide,
    isHtml,
  };

  try {
    const doc = await ProfileProxy.findOneById(appId, id);

    if (!doc) {
      await ProfileProxy.create(appId, data);
    } else {
      await ProfileProxy.update(appId, id, data);
    }

    successJson(req, res, { msg: ResultMsg.UPDATE_SUCCESS });
  } catch (err) {
    next(err);
  }
}

async function create(req, res, next) {
  const appId = res.locals.appId;
  const guide = validator.trim(req.body.guide || '');
  const isHtml = req.body.isHtml || false;

  try {
    await ProfileProxy.create(appId, guide, isHtml);
    successJson(req, res, { msg: ResultMsg.CREATE_SUCCESS });
  } catch (err) {
    next(err);
  }
}
